package com.heartunderblade.rpc.StaticProxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.heartunderblade.rpc.RpcPojo.RpcRequest;
import com.heartunderblade.rpc.RpcPojo.RpcResponse;
import com.heartunderblade.rpc.pojo.User;
import com.heartunderblade.rpc.service.Serializer;
import com.heartunderblade.rpc.service.UserService;
import com.heartunderblade.rpc.service.impl.JdkSerializer;

import java.io.IOException;

public class UserServiceProxy implements UserService {
    @Override
    public User getUser(User user) {
        // 指定序列化器
        final Serializer serializer = new JdkSerializer();
        System.out.println("静态代理");

        // 构造RpcRequest对象
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setServiceName(UserService.class.getName());
        rpcRequest.setMethodName("getUser");
        rpcRequest.setArgsType(new Class[]{User.class});
        rpcRequest.setArgs(new Object[]{user});
        System.out.println(rpcRequest);
        // 序列化
        byte[] bytes = null;
        try {
            bytes = serializer.serialize(rpcRequest);
            //发送请求
            HttpResponse response = HttpRequest.post("http://localhost:8090")
                    .contentType("application/octet-stream")  // 设置为二进制流
                    .body(bytes)
                    .execute();
            //获得请求结果对象
            byte[] resBytes = response.bodyBytes();
            //反序列化为对象
            RpcResponse result = serializer.deserialize(resBytes, RpcResponse.class);
            return (User) result.getData();
            // 发送请求
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
